<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Lauthz\Exceptions\UnauthorizedException;
use Lauthz\Facades\Enforcer;

class EnforcerMiddleware
{
    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/2 14:57
     * @Description:权限校验
     * @param $request
     * @param Closure $next
     * @param null $guard
     * @return mixed
     */
    public function handle($request, Closure $next,$guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            throw new UnauthorizedException();
        }

        $user_id = Auth::user($guard)->getAuthIdentifier();
        //顶级管理员直接略过校验
        if($guard =="backend" && $user_id == 1) {
            return $next($request);
        }
        //用户或管理员id作为唯一标识
        $guard_id='user_id.' . $user_id;

        if($guard) {
            $guard_id= $guard.'.' . $guard_id;
        }

        //使用路由名称跟用户id匹配
        //$route_name=Route::currentRouteName();
        if (!Enforcer::enforce($guard_id, $request->route()->getName(), $request->method())) {
            throw new UnauthorizedException();
        }
        return $next($request);
    }
}
